package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Borrow;
import com.example.demo.service.IBorrowService;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;


@RestController
@RequestMapping("/borrow")
public class BorrowController {
    @Autowired
    private IBorrowService borrowService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/save")
    public Result save(@RequestBody Borrow obj) {
        //前端传入用户id和书名或书的id生成订单信息并更改图书表中的库存
        return borrowService.saveBorrow(obj);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Borrow obj) {
        System.out.println(obj.getId());
        borrowService.updateById(obj);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        return borrowService.removeByIdBorrow(id);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Borrow obj = borrowService.getById(id);
        return Result.success(obj);
    }

    @GetMapping("/list")
    public Result list() {
        List<Borrow> list = borrowService.list();
        return Result.success(list);
    }

    //还书方法
    @PostMapping("/saveRetur")
    public Result saveRetur(@RequestBody Borrow obj) {
        redisTemplate.opsForValue().set("latest_order_time", LocalDateTime.now());
        return borrowService.saveRetur(obj);
    }


    @GetMapping("/page")
    public Result search(@RequestParam(required = false) Integer userId,
                         @RequestParam(required = false) String userName,
                         @RequestParam(required = false) Integer bookId,
                         @RequestParam(required = false) String bookName,
                         @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                         @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        IPage<Borrow> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Borrow> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("borrow_date");
        if (userId != null) {
            wrapper.like("user_id", userId);
        }
        if (userName != null) {
            wrapper.like("user_name", userName);
        }
        if (bookId != null) {
            wrapper.like("book_id", bookId);
        }
        if (bookName != null) {
            wrapper.like("book_name", bookName);
        }
        IPage<Borrow> borrowIPage = borrowService.page(page, wrapper);
        return Result.success(borrowIPage);
    }

    //TODO
    //借书方法
    //前端传入用户id和书的id生成订单信息并更改图书表中的库存
    @PostMapping("/saveBorrow")
    public Result saveBorrow(@RequestBody Borrow obj) {
        System.out.println(obj);
        redisTemplate.opsForValue().set("latest_order_time", LocalDateTime.now());
        return borrowService.saveBorrow(obj);
    }

    //上传订单xlsl文件的格式
    @PostMapping("/import")
    public ResponseEntity<String> importExcel(@RequestParam("file") MultipartFile file) throws IOException, ParseException {
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);
        List<Borrow> borrows = new ArrayList<>();
        // 遍历 Excel 行并将数据导入到应用程序中
        for (Row row : sheet) {
            //根据表头判断要保存的字段
            if (row.getRowNum() == 0) {
                continue;
            }
            // 读取 Excel 行中的数据
            int userIdStr = (int) row.getCell(0).getNumericCellValue();
            int bookIdStr = (int) row.getCell(1).getNumericCellValue();
            Date borrowDate;
            Date dueDate;
            Date returnDate;
            if (row.getCell(2).getCellType() == CellType.NUMERIC) {
                borrowDate = row.getCell(2).getDateCellValue();
            } else {
                String borrowDateStr = row.getCell(2).getStringCellValue();
                borrowDate = new SimpleDateFormat("yyyy-MM-dd").parse(borrowDateStr);
            }
            if (row.getCell(3).getCellType() == CellType.NUMERIC) {
                dueDate = row.getCell(3).getDateCellValue();
            } else {
                String dueDateStr = row.getCell(3).getStringCellValue();
                dueDate = new SimpleDateFormat("yyyy-MM-dd").parse(dueDateStr);
            }
            if (row.getCell(4).getCellType() == CellType.NUMERIC) {
                returnDate = row.getCell(4).getDateCellValue();
            } else {
                String returnDateStr = row.getCell(4).getStringCellValue();
                returnDate = new SimpleDateFormat("yyyy-MM-dd").parse(returnDateStr);
            }
            String status = row.getCell(5).getStringCellValue();
            String userMajor = row.getCell(6).getStringCellValue();
            int userGradeStr = (int) row.getCell(7).getNumericCellValue();

            // 进行数据清洗
            Integer userId;
            Integer bookId;
            Integer userGrade;

            try {
                userId = userIdStr;
                bookId = bookIdStr;
                userGrade = userGradeStr;
            } catch (NumberFormatException e) {
                // 如果数据不符合预期，忽略该行
                continue;
            }
            // 创建借阅记录对象并添加到列表中
            Borrow borrow = new Borrow();
            borrow.setUserId(userId);
            borrow.setBookId(bookId);
            borrow.setBorrowDate(borrowDate);
            borrow.setDueDate(dueDate);
            borrow.setReturnDate(returnDate);
            borrow.setStatus(status);
            borrow.setUserMajor(userMajor);
            borrow.setUserGrade(userGrade);
            borrows.add(borrow);
        }
        // 将数据保存到 borrow 表中
        List<Borrow> savedBorrows = borrowService.saveAll(borrows);
        if (savedBorrows.size() == borrows.size()) {
            return ResponseEntity.ok("Excel 导入成功");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Excel 导入失败");
        }
    }

    @PostMapping("/borrow/import")
    public ResponseEntity<?> importBorrowData(@RequestParam("file") MultipartFile file) {
        System.out.println(1);
        // 处理文件上传
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                // 处理上传的文件数据
                return ResponseEntity.ok().build();
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    //根据用户id查询相关借阅数据
    @GetMapping("/userList")
    public Result listByUserId(@RequestParam Integer id,
                               @RequestParam(name = "bookName",required = false) String bookName,
                               @RequestParam(name = "bookNo",required = false) Integer bookNo,
                               @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                               @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        //分页查询
        IPage<Borrow> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Borrow> wrapper = new QueryWrapper<>();
        if (bookName != null) wrapper.like("book_name", bookName);
        if (bookNo != null) wrapper.like("book_id", bookNo);
        wrapper.eq("user_id", id);
        wrapper.orderByDesc("borrow_date");
        IPage<Borrow> borrowIPage = borrowService.page(page, wrapper);
        return Result.success(borrowIPage);
    }
}
